package com.hao.shirojwt.util.lock.impl;


import com.hao.shirojwt.util.lock.Lock;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisLockImpl implements Lock {
    @Resource
    private RedissonClient redissonClient;

    @Override
    public Boolean tryLock(String name, long waitTime) {
        return tryLock(name, waitTime, TimeUnit.MINUTES);
    }

    @Override
    public Boolean tryLock(String name, long waitTime, TimeUnit unit) {
        RLock lock = this.redissonClient.getLock(name);
        boolean tryLock = false;

        try {
            tryLock = lock.tryLock(waitTime, unit);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }

        log.info("redis加锁状态name: {}, status: {}", name, tryLock);
        return tryLock;
    }

    @Override
    public void unlock(String name) {
        RLock lock = this.redissonClient.getLock(name);
        boolean locked = lock.isLocked();
        if (locked) {
            lock.unlock();
            log.info("redis解锁名称name:{}", name);
        } else {
            log.info("未加锁name:{}", name);
        }
    }
}
